//
//  HAJSBridgeHandler.m
//  HAFund
//
//  Created by 夏成龙 on 2018/11/12.
//  Copyright © 2018年 夏成龙. All rights reserved.
//

#import "HAJSBridgeHandler.h"
#import "HAJSBridgeHandlerEvent.h"

#import "JSBridgeHandlerProtocol.h"

NSString *const handlerMessageMethod = @"handlerMessage";

@interface HAJSBridgeHandler ()<WKScriptMessageHandler>

@property (weak, nonatomic) id <JSBridgeHandlerProtocol> bridgeDelegate;
@property (weak, nonatomic) WKWebView *webView;
/// 交互事件
@property (strong, nonatomic) HAJSBridgeHandlerEvent *handlerEvent;
@end

@implementation HAJSBridgeHandler

- (instancetype)initWithBridgeDelegate:(id)bridgeDelegate webView:(WKWebView *)webView {
    if ([super init]) {
        _bridgeDelegate = bridgeDelegate;
        _webView = webView;
        
        NSString *jsPath = [[NSBundle mainBundle] pathForResource:@"bridge" ofType:@"js"];
        NSString *handlerJs = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:nil];
        // 注入交互js
        WKUserScript *script = [[WKUserScript alloc] initWithSource:handlerJs injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
        [_webView.configuration.userContentController addUserScript:script];
        // 添加交互函数
        [_webView.configuration.userContentController addScriptMessageHandler:self name:handlerMessageMethod];
        _handlerEvent = [[HAJSBridgeHandlerEvent alloc] init];
    }
    return self;
}

- (void)evaluateJavaScriptWithMethodName:(NSString *)methodName params:(id)params completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))handler {
    if (methodName.length <= 0) {
        return;
    }
    NSString *jsString = methodName;
    if (!params) {
        NSString *paramsString = [self getParmasString:params];
        jsString = [NSString stringWithFormat:@"%@(%@)", methodName, paramsString];
    }
    
    WKWebView *strongWebView = self.webView;
    [self.webView evaluateJavaScript:jsString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSString *title = strongWebView.title;
        NSLog(@"%@", title);
        if (handler) {
            handler(result, error);
        }
    }];
}

- (NSString *)getParmasString:(id)params {
    if (!params) {
        return @"";
    }
    if ([params isKindOfClass:NSString.class]) {
        return params;
    }
    
    if ([params isKindOfClass:NSDictionary.class]) {
        NSMutableString *mStr = [NSMutableString string];
        [mStr appendString:@"{"];
        NSDictionary *paramDict = params;
        for (NSString *key in paramDict) {
            NSString *value = paramDict[key];
            [mStr appendFormat:@"%@:%@", key, value];
        }
        [mStr appendString:@"}"];
        return mStr;
    }
    return @"";
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if (![message.name isEqualToString:handlerMessageMethod]) {
        return;
    }
    // 1.生成事件对象
    HAJSEvent *event = [[HAJSEvent alloc] initWithEventParmas:message.body];
    event.handlerEvent = self.handlerEvent;
    event.handler = self;
    event.bridgeHandler = self.bridgeDelegate;
    [self.handlerEvent bridgeResponseEvnetWithEvnet:event];
}

@end
